import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
GRID_SIZE = 9
GRID_WIDTH = 50
WINDOW_WIDTH = GRID_SIZE * GRID_WIDTH
WINDOW_HEIGHT = GRID_SIZE * GRID_WIDTH
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("围住神经猫")

# 初始化棋盘
board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
# 神经猫初始位置
cat_x = GRID_SIZE // 2
cat_y = GRID_SIZE // 2
board[cat_x][cat_y] = 2

# 绘制棋盘
def draw_board():
    screen.fill(WHITE)
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            pygame.draw.rect(screen, BLACK, (j * GRID_WIDTH, i * GRID_WIDTH, GRID_WIDTH, GRID_WIDTH), 1)
            if board[i][j] == 1:
                pygame.draw.rect(screen, RED, (j * GRID_WIDTH + 5, i * GRID_WIDTH + 5, GRID_WIDTH - 10, GRID_WIDTH - 10))
            elif board[i][j] == 2:
                pygame.draw.circle(screen, GREEN, (j * GRID_WIDTH + GRID_WIDTH // 2, i * GRID_WIDTH + GRID_WIDTH // 2),
                                   GRID_WIDTH // 2 - 5)

# 检查神经猫是否被围住
def is_cat_surrounded():
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for dx, dy in directions:
        new_x = cat_x + dx
        new_y = cat_y + dy
        if 0 <= new_x < GRID_SIZE and 0 <= new_y < GRID_SIZE and board[new_x][new_y] == 0:
            return False
    return True

# 神经猫移动
def move_cat():
    global cat_x, cat_y
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    valid_moves = []
    for dx, dy in directions:
        new_x = cat_x + dx
        new_y = cat_y + dy
        if 0 <= new_x < GRID_SIZE and 0 <= new_y < GRID_SIZE and board[new_x][new_y] == 0:
            valid_moves.append((new_x, new_y))
    if valid_moves:
        new_x, new_y = random.choice(valid_moves)
        board[cat_x][cat_y] = 0
        cat_x = new_x
        cat_y = new_y
        board[cat_x][cat_y] = 2

# 主游戏循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            grid_x = y // GRID_WIDTH
            grid_y = x // GRID_WIDTH
            if board[grid_x][grid_y] == 0:
                board[grid_x][grid_y] = 1
                if not is_cat_surrounded():
                    move_cat()

    draw_board()
    if is_cat_surrounded():
        font = pygame.font.Font(None, 36)
        text = font.render("你成功围住了神经猫！", True, BLACK)
        screen.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 2 - text.get_height() // 2))
        pygame.display.flip()
        pygame.time.wait(2000)
        running = False

    pygame.display.flip()

# 退出 Pygame
pygame.quit()